import type * as Ts from 'typescript';
import { defineRule } from '@tsslint/config';
import type { Rule, RuleContext } from '@tsslint/config';
function noConsole(): Rule {
  return defineRule(
    ({
      typescript: ts,
      sourceFile,
      reportWarning,
      languageService: ls,
    }: RuleContext) => {
      const Warning_Title = "Calls to 'console.x' are not allowed.";
      const Fix_Title = 'Remove this console expression';
      ts.forEachChild(sourceFile, function cb(node: Ts.Node) {
        if (
          (ts.isPropertyAccessExpression(node) ||
            ts.isElementAccessExpression(node)) /* a.b.c */ &&
          ts.isIdentifier(node.expression) /* node.expression: console */ &&
          node.expression.text === 'console'
        ) {
          // const tsconfig = ts.findConfigFile(process.cwd(), ts.sys.fileExists, "tsconfig.json")
          const consoleType = ls.getTypeDefinitionAtPosition(
            sourceFile.fileName,
            node.getStart(sourceFile),
          )?.[0];

          if (!consoleType || consoleType.name !== 'Console') {
            return;
          }
          reportWarning(
            Warning_Title + `${consoleType.kind}`,
            node.parent.getStart(sourceFile),
            node.parent.getEnd(),
          ).withFix(Fix_Title, () => [
            {
              fileName: sourceFile.fileName,
              textChanges: [
                {
                  newText: `/* __DELETE__ ${node.parent.getText()}: ${consoleType.name ?? ''} */`,
                  span: {
                    start: node.parent.getStart(sourceFile),
                    length: node.parent.getWidth(sourceFile),
                  },
                },
              ],
            },
          ]);
        }
        ts.forEachChild(node, cb);
      });
    },
  );
}
export default noConsole;
